package com.fenghuajueli.lib_data.database.manager;

import android.content.Context;

import com.fenghuajueli.lib_data.database.DaoManager;
import com.fenghuajueli.lib_data.entity.db.LocalDraftEntity;
import com.fenghuajueli.lib_data.entity.db.LocalDraftEntityDao;

import java.util.List;

/**
 * 草稿箱记录表
 */
public class DraftsManager {
    private DaoManager manager;

    public DraftsManager(Context context) {
        manager = DaoManager.getInstance();
        manager.init(context);
    }


    public boolean insertData(LocalDraftEntity localDraftEntity) {
        return manager.getDaoSession().insertOrReplace(localDraftEntity) != -1;
    }

    /**
     * 插入多条记录，需要开辟新的线程
     *
     * @param LocalDraftEntityList
     * @return flag
     **/
    public boolean insertList(final List<LocalDraftEntity> LocalDraftEntityList) {
        boolean flag = false;
        try {
            manager.getDaoSession().runInTx(() -> {
                for (LocalDraftEntity LocalDraftEntity : LocalDraftEntityList) {
                    manager.getDaoSession().insertOrReplace(LocalDraftEntity);
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    public boolean updateData(LocalDraftEntity LocalDraftEntity) {
        boolean flag = false;
        try {
            manager.getDaoSession().update(LocalDraftEntity);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * @param LocalDraftEntity
     * @return flag
     */
    public boolean delete(LocalDraftEntity LocalDraftEntity) {
        boolean flag = false;
        try {
            manager.getDaoSession().delete(LocalDraftEntity);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    public void deleteAll(Class cls) {
        manager.getDaoSession().deleteAll(cls);
    }

    /**
     * 返回多行记录 * * @return
     */
    public List<LocalDraftEntity> listAll() {
        return manager.getDaoSession().getLocalDraftEntityDao().queryBuilder().orderDesc(LocalDraftEntityDao.Properties.ModifyTime).list();
    }

    /**
     * 按照主键返回单行记录 * * @param key * @return
     */
    public LocalDraftEntity getOneData(long key) {
        return manager.getDaoSession().load(LocalDraftEntity.class, key);
    }

    /**
     * 查询短语表中所有数据
     */
    public List<LocalDraftEntity> queryAll() {
        return manager.getDaoSession().loadAll(LocalDraftEntity.class);
    }


}
